//
//  BatchimportViewController.m
//  SafeFoodManagerDemo
//
//  Created by ios-1 on 2018/3/13.
//  Copyright © 2018年 bob. All rights reserved.
//

#import "BatchimportViewController.h"
#import "GoodListModel.h"
#import "GoodListTableViewCell.h"
#import "GetRegisterInforModel.h"
#import "ShopRegisterViewController.h"
@interface BatchimportViewController ()
@property(nonatomic,copy)NSString*SearchKeyWord;
@property(nonatomic,strong)UIView *footView;
@end

@implementation BatchimportViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.btn.selected = NO;
    [self GotoEdit:self.btn];
    
    self.homeTableView.estimatedRowHeight=70;
    
    [self.homeTableView registerNib:[UINib nibWithNibName:@"GoodListTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    [self.homeTableView.mj_header beginRefreshing];
    
    
    [self.view addSubview:self.footView];
    // Do any additional setup after loading the view.
}


#pragma mark-tablevie代理方法


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    GoodListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        
    cell.isClick=YES;
    cell.deleStatue=YES;//是否编辑状态
    
    if(self.is_goodType)
    {
        GoodCataData *data=self.dataArr[indexPath.row];
        cell.CataModel = data;
    }else{
        GoodListData *data=self.dataArr[indexPath.row];
        cell.listModel=data;
    }
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewAutomaticDimension;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if(self.is_goodType)
    {
        GoodCataData *data=self.dataArr[indexPath.row];
        data.Seleclt=!data.Seleclt;
    }else{
        GoodListData *data=self.dataArr[indexPath.row];
        data.Seleclt=!data.Seleclt;
    }
   
    [self ChangeStatues];
    
    [self.homeTableView reloadData];
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

-(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return @"删除";

}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete;
    
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (editingStyle==UITableViewCellEditingStyleDelete) {

        GoodListData *data=self.dataArr[indexPath.row];

        NSMutableArray *arr=[NSMutableArray array];

        [arr addObject:[NSString stringWithFormat:@"%ld",data.goodsId]];

        [self SavePostion:arr];

    }

}

#pragma mark 批量导入商品
-(void)SavePostion:(NSArray*)PostID
{
    NSString *params=[HelpWay arrToJSON:PostID];
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/commonProductImport.json" andrequestTime:5 andParams:@{@"goodsIds":params,@"shopId":[NSString stringWithFormat:@"%zd",self.shopId]} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
            [MBProgressHUD showSuccessMessage:@"导入成功"];
            
            [self.homeTableView.mj_header beginRefreshing];
            
            //注册导入成功的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SaveSuccessnote" object:nil];
//            if (self.deleStatue) {
//                //如果处于删除状态
//                [self GotoEdit:self.btn];
//            }
        }else if (responseStatus==0)
        {
            
            [MBProgressHUD showErrorMessage:message];
            
        }else if (responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
    }];
    
    
}

#pragma mark 批量导入分类
-(void)SaveTypePostion:(NSArray*)PostID
{
    NSString *params=[HelpWay arrToJSON:PostID];
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/commonProductTypeImport.json" andrequestTime:5 andParams:@{@"catIds":params,@"shopId":[NSString stringWithFormat:@"%zd",self.shopId]} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        
        
        
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
            [MBProgressHUD showSuccessMessage:@"导入成功"];
            
            [self.homeTableView.mj_header beginRefreshing];
            
            //注册导入成功的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SaveSuccessnote" object:nil];
            
            //            if (self.deleStatue) {
            //                //如果处于删除状态
            //                [self GotoEdit:self.btn];
            //            }
        }else if (responseStatus==0)
        {
            
            [MBProgressHUD showErrorMessage:message];
            
        }else if (responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
    }];
}

#pragma mark-跳转事件
-(void)PushChangeStatueVC
{
    BOOL isSelf=self.Reqmodel.shopId==0?YES:NO;
    
    BaseSearchChooseViewController *Choose=[[BaseSearchChooseViewController alloc]init];
    
    Choose.ReqStr=[SearchAndChooseManager getChooseUrlWithType:ProductStyleType];
    
    Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:ProductStyleType andIsLookSelf:isSelf];
    
    Choose.SearchPlace=self.searchName;
    
    Choose.KeyWord=self.SearchKeyWord;
    
    Choose.SureBlock=^(NSString *paras,NSString*keyword)
    {
        self.SearchKeyWord=keyword;
        
        self.Reqmodel.params=paras;
        
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:Choose animated:YES];
}
#pragma mark-编辑事件
-(void)GotoEdit:(UIButton*)sender
{
    sender.selected=!sender.selected;
    
    self.deleStatue=sender.selected;
    
    if (!self.deleStatue) {
        
        if(self.is_goodType)
        {
            for (GoodCataData *data in self.dataArr) {
                
                data.Seleclt=NO;
            }
        }else{
            for (GoodListData *data in self.dataArr) {
                
                data.Seleclt=NO;
            }
        }
        
        
        [self ChangeStatues];
    }
    
    [self.homeTableView reloadData];
}


-(void)SeletAll
{
    if(self.is_goodType)
    {
        for (GoodCataData *data in self.dataArr) {
            
            data.Seleclt=YES;
        }
    }else{
        for (GoodListData *data in self.dataArr) {
            
            data.Seleclt=YES;
        }
    }
    
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//全选

-(void)CanseletAll{
    
    if(self.is_goodType)
    {
        for (GoodCataData *data in self.dataArr) {
            
            data.Seleclt=NO;
        }
    }else{
        for (GoodListData *data in self.dataArr) {
            
            data.Seleclt=NO;
        }
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//取消全选

-(void)DelectAll
{
    NSMutableArray *arr=[NSMutableArray array];
    
    if(self.is_goodType)
    {
        for (GoodCataData *data in self.dataArr) {
            
            if (data.Seleclt) {
                
                [arr addObject:[NSString stringWithFormat:@"%ld",data.catId]];
            }
        }
    }else{
        for (GoodListData *data in self.dataArr) {
            
            if (data.Seleclt) {
                
                [arr addObject:[NSString stringWithFormat:@"%ld",data.goodsId]];
            }
        }
    }
    
    
    if (arr.count==0) {
        
        [MBProgressHUD showWarnMessage:@"请至少选择一项"];
        
        return;
    }
    
    if(self.is_goodType)
    {
        [self SaveTypePostion:arr];
    }else{
        [self SavePostion:arr];
    }
    
}//全部删除


-(void)ChangeStatues{
    
    NSInteger i=0;
    if(self.is_goodType)
    {
        for (GoodCataData *data in self.dataArr) {
            
            if (data.Seleclt) {
                i++;
            }
        }
    }else{
        for (GoodListData *data in self.dataArr) {
            
            if (data.Seleclt) {
                i++;
            }
        }
    }
    
    self.DeleView.tag = 999999;
    [self.DeleView SelectNum:i];
}

//#pragma mark-新增事件
//-(void)addNewgoods
//{
//    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"新增商品",@"批量导入", nil];
//    [sheet showInView:self.view];
//
//}


#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self.homeTableView.mj_header beginRefreshing];
    
}


/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
    self.Reqmodel.currentPage=1;
    
    [self.homeTableView.mj_footer resetNoMoreData];
    
    if(self.is_goodType)
    {
        [self loadTypeDatas];
    }else{
        [self loadDatas];
    }
    
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
    self.Reqmodel.currentPage++;
    
    if(self.is_goodType)
    {
        [self loadTypeDatas];
    }else{
        [self loadDatas];
    }
}

-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/commonProductList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        GoodListModel *InforModel=[GoodListModel mj_objectWithKeyValues:responseObject];
        
        if (responseStatus==1) {
            //请求成功
            
            NSLog(@"%@",[HelpWay dictionaryToJSON:responseObject]);
            
            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",InforModel.totalRecord,@"商品"];
            
            if (InforModel.data.count==0&&self.Reqmodel.currentPage==1) {
                
                [self.dataArr removeAllObjects];
                
                [self.homeTableView reloadData];
                
                
                
                self.Type=TBNODateType;
                
                if (self.deleStatue) {
                    //如果处于删除状态
                    [self GotoEdit:self.btn];
                }
                
                self.btn.hidden=YES;
                self.footView.hidden = YES;
            }else if (InforModel.data.count==0&&self.Reqmodel.currentPage!=1){
                
                self.btn.hidden=NO;
                self.footView.hidden = NO;
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else{
                
                self.btn.hidden=NO;
                self.footView.hidden = NO;
                
                if (self.Reqmodel.currentPage==1) {
                    
                    [self.dataArr removeAllObjects];
                    
                }
                
                [self.dataArr addObjectsFromArray:InforModel.data];
                
                [self.homeTableView reloadData];
                
            }
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
    
    
}

-(void)loadTypeDatas
{
    [self showLoadingAnimation];

    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/commonProductTypeList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        GoodCataModel *InforModel=[GoodCataModel mj_objectWithKeyValues:responseObject];
        
        if (responseStatus==1) {
            //请求成功
            
            DLog(@"%@",[HelpWay dictionaryToJSON:responseObject]);
            
            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",InforModel.totalRecord,@"商品"];
            
            if (InforModel.data.count==0&&self.Reqmodel.currentPage==1) {
                
                [self.dataArr removeAllObjects];
                
                [self.homeTableView reloadData];
                
    
                self.Type=TBNODateType;
                
                if (self.deleStatue) {
                    //如果处于删除状态
                    [self GotoEdit:self.btn];
                }
                
                self.btn.hidden=YES;
                self.footView.hidden = YES;
            }else if (InforModel.data.count==0&&self.Reqmodel.currentPage!=1){
                
                self.btn.hidden=NO;
                self.footView.hidden = NO;
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else{
                
                self.btn.hidden=NO;
                self.footView.hidden = NO;
                
                if (self.Reqmodel.currentPage==1) {
                    
                    [self.dataArr removeAllObjects];
                    
                }
                
                [self.dataArr addObjectsFromArray:InforModel.data];
                
                [self.homeTableView reloadData];
                
            }
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
    
    
}
- (UIView*)footView
{
    if(_footView == nil)
    {
        _footView = [[UIView alloc]init];
        if (kDevice_Is_iPhoneX) {
            
            _footView.frame=CGRectMake(0, SCREEN_HEIGHT-45*SCREEN_WIDTH/320-64-34, SCREEN_WIDTH, 45*SCREEN_WIDTH/320);
        }else{
            _footView.frame=CGRectMake(0, SCREEN_HEIGHT-45*SCREEN_WIDTH/320-64, SCREEN_WIDTH, 45*SCREEN_WIDTH/320);
        }
        _footView.backgroundColor = [UIColor whiteColor];
        
        UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        confirmBtn.frame = CGRectMake(0, 0, kScreenWidth/2, CGRectGetHeight(_footView.frame));
        confirmBtn.backgroundColor = TBColorProvideBtnbg;
        confirmBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [confirmBtn setTitle:@"全选" forState:UIControlStateNormal];
        [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [confirmBtn addTarget:self action:@selector(slectAll:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:confirmBtn];
        
        UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        nextBtn.frame = CGRectMake(CGRectGetMaxX(confirmBtn.frame), 0, kScreenWidth/2, CGRectGetHeight(_footView.frame));
        nextBtn.backgroundColor = RGBCOLOR(255, 211, 52);
        nextBtn.titleLabel.font = [UIFont systemFontOfSize:16];
        [nextBtn setTitle:@"确定" forState:UIControlStateNormal];
        [nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [nextBtn addTarget:self action:@selector(DelectAll) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:nextBtn];
        
    }
    return _footView;
}

- (void)slectAll:(UIButton*)sender
{
    sender.selected = !sender.selected;
    if(sender.selected)
    {
        [self SeletAll];
    }else{
        [self CanseletAll];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
